# -*- coding: utf-8 -*-

import sys

CACHED_DAO = {}

def dao_factory(dao_name):
    assert isinstance(dao_name,(str,unicode))
    cache_key = dao_name

    if CACHED_DAO.has_key(cache_key):
        return CACHED_DAO[cache_key]

    else:
        import dao
        try:
            assert(hasattr(sys.modules["dao"],cache_key))
            dao = getattr(sys.modules["dao"],cache_key)
            dao = dao()
        except:
            print 'dao name is',cache_key
            raise

        CACHED_DAO[cache_key] = dao
        return dao


CACHED_DECORATOR_DAO = {}
def dao_decorator_factory(dao_name):
    assert isinstance(dao_name,(str,unicode))
    cache_key = dao_name

    if CACHED_DECORATOR_DAO.has_key(cache_key):
        return CACHED_DECORATOR_DAO[cache_key]

    else:
        import dao
        import modeldecorator
        try:
            assert(hasattr(sys.modules["dao"],cache_key))
            dao = getattr(sys.modules["dao"],cache_key)
            dao = dao()
        except:
            print 'dao name is',cache_key
            raise

        decorator = dao.decorator if dao.decorator else []

        try:
            for d,args in decorator:
                assert(hasattr(sys.modules["modeldecorator"],d))
                dao = getattr(sys.modules["modeldecorator"],d)(dao,args)
        except:
            raise

        CACHED_DECORATOR_DAO[cache_key] = dao
        return dao

